<template>
  <el-card>
    <div slot="header" style="font-size: 18px">试题录入</div>
    <el-form
      ref="form"
      label-width="80px"
      :model="formData"
      style="margin-left: 50px"
      :rules="rules"
    >
      <!-- 学科 -->
      <el-form-item label="学科:" prop="subjectID">
        <el-select
          v-model="formData.subjectID"
          placeholder="请选择"
          style="width: 400px"
          @change="subValueChange($event)"
        >
          <el-option
            v-for="item in formList.subData"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <!-- 目录 -->
      <el-form-item label="目录:" prop="catalogID">
        <el-select
          v-model="formData.catalogID"
          style="width: 400px"
          placeholder="请选择"
        >
          <el-option
            v-for="item in formList.secondData"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <!-- 企业 -->
      <el-form-item label="企业:" prop="enterpriseID">
        <el-select
          v-model="formData.enterpriseID"
          style="width: 400px"
          placeholder="请选择"
        >
          <el-option
            v-for="item in formList.companys"
            :key="item.id"
            :label="item.company"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <!-- 城市 -->
      <el-form-item label="城市:" prop="province">
        <el-row style="width: 400px">
          <el-col class="left_input" :span="12">
            <el-select
              v-model.trim="formData.province"
              placeholder="请选择"
              class="select_one"
              @change="changeFn"
            >
              <el-option
                v-for="(item, index) in provincesList"
                :key="index"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-col>
          <el-col :span="12">
            <el-select
              v-model="formData.city"
              placeholder="请选择"
              class="select_one"
            >
              <el-option
                v-for="(item, index) in citysList"
                :key="index"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-col>
        </el-row>
      </el-form-item>
      <!-- 方向 -->
      <el-form-item label="方向:" prop="direction">
        <el-select
          v-model="formData.direction"
          style="width: 400px"
          placeholder="请选择"
        >
          <el-option
            v-for="(item, index) in formList.directionData"
            :key="index"
            :label="item.value"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <!-- 题型 -->
      <el-form-item label="题型:" prop="questionType">
        <el-radio-group v-model="formData.questionType">
          <el-radio :label="'1'">单选</el-radio>
          <el-radio :label="'2'">多选</el-radio>
          <el-radio :label="'3'">简答</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 难度 -->
      <el-form-item label="难度:" prop="difficulty">
        <el-row>
          <el-radio-group v-model="formData.difficulty">
            <el-radio :label="'1'">简单</el-radio>
            <el-radio :label="'2'">一般</el-radio>
            <el-radio :label="'3'">困难</el-radio>
          </el-radio-group>
        </el-row>
      </el-form-item>
      <!-- 题干 -->
      <el-form-item label="题干:" prop="question">
        <quillEditor
          v-model="formData.question"
          :options="editorOptions"
          style="height: 200px; margin-bottom: 60px"
        />
      </el-form-item>
      <!-- 题干 -->
      <el-form-item
        v-if="formData.questionType !== '3'"
        label="选项:"
        prop="optionVal"
      >
        <!-- 单选框 -->
        <el-radio-group
          v-if="formData.questionType === '1'"
          v-model="formData.optionVal"
        >
          <el-radio
            v-for="(item, index) in formList.options"
            :key="index"
            :label="item.code"
            style="display: block; margin-top: 20px"
            class="group"
            @change="radioValueChange($event)"
          >{{ item.code }} :
            <el-input
              v-model="item.title"
              style="margin-left: 10px; width: 233px"
            />
            <!-- 图片上传 -->
            <uploadImg class="Img" />
          </el-radio>
        </el-radio-group>
        <!-- 多选框 -->
        <el-checkbox-group
          v-if="formData.questionType === '2'"
          v-model="formData.optionsVal"
        >
          <el-checkbox
            v-for="(item, index) in formList.options"
            :key="index"
            :label="item.code"
            :value="item.code"
            :checked="item.isRight"
            style="display: block; margin-top: 20px"
            class="group"
            @change="item.isRight = !item.isRight"
          >{{ item.code }} :
            <el-input
              v-model="item.title"
              style="margin-left: 10px; width: 246px"
            />
            <!-- 图片上传 -->
            <uploadImg class="Img" />
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item>
        <el-button
          :disabled="formData.questionType !== '2'"
          type="danger"
          size="medium"
          @click="addChild"
        >+增加选项与答案</el-button>
      </el-form-item>
      <el-form-item label="解析视频:" prop="videoURL">
        <el-input v-model="formData.videoURL" style="width: 400px" />
      </el-form-item>
      <el-form-item label="答案解析:" prop="answer">
        <quillEditor
          v-model="formData.answer"
          :options="editorOptions"
          style="height: 200px; margin-bottom: 65px"
        />
      </el-form-item>
      <el-form-item label="题目备注:" prop="remarks">
        <textarea
          v-model="formData.remarks"
          rows="4"
          style="width: 400px; min-height: 33px"
        />
      </el-form-item>
      <el-form-item label="试题标签" prop="tags">
        <el-select
          ref="label"
          v-model="formData.tags"
          style="width: 400px"
          placeholder="请选择"
        >
          <el-option
            v-for="item in formList.labelList"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          v-if="!$route.params.id"
          type="primary"
          @click="addClick"
        >确定添加</el-button>
        <el-button v-else type="success" @click="editClick">确定修改</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { provinces, citys } from '@/assets/city'
import { getSubjectsAPI, getSubjectsListAPI, getCompanyListAPI, getlabelListAPI, addBasicQuestionAPI, getBasicQuestionDetailAPI, updateBasicQuestionAPI } from '@/api/index'
import uploadImg from './components/UploadImg.vue';
import { quillEditor } from 'vue-quill-editor';
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
export default {
	name: 'TestInput',
	components: {
		quillEditor,
		uploadImg
	},
  data() {
    return {
      provincesList: provinces(), // 城市
      citysList: [], // 地区
      formList: {
        subData: [], // 学科列表
        secondData: [], // 目录列表
        tagsData: [], // 标签列表
        companys: [], // 企业列表
        labelList: [], // 标签列表
        directionData: [
          {
            value: 'o2o'
          },
          {
            value: '外包服务'
          },
          {
            value: '企业服务'
          },
          {
            value: '互联网金融'
          },
          {
            value: '企业咨询'
          },
          {
            value: '互联网'
          },
          {
            value: '电子商务'
          },
          {
            value: '其他'
          }
        ], // 方向
        options: [
          {
            isRight: false,
            code: 'A',
            title: '',
            img: ''
          },
          {
            isRight: false,
            code: 'B',
            title: '',
            img: ''
          },
          {
            isRight: false,
            code: 'C',
            title: '',
            img: ''
          },
          {
            isRight: false,
            code: 'D',
            title: '',
            img: ''
          }
        ]
      },
      formData: {
        subjectID: '', // 学科数据
        catalogID: '', // 目录数据
        enterpriseID: '', // 企业列表
        province: '', // 城市
        city: '', // 地区
        direction: '', // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        optionVal: '', // 选项
        optionsVal: [], // 选项
        tags: '', // 试题标签
        videoURL: '', // 解析视频
        question: '', // 提干
        answer: '', // 答案解析
        remarks: '', // 备注
        isRight: ''
      },
      rules: {
        subjectID: [{ required: true, message: '请选择学科', trigger: 'blur' }],
        catalogID: [{ required: true, message: '请选择目录', trigger: 'blur' }],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'blur' }
        ],
        province: [{ required: true, message: '请选择省份', trigger: 'blur' }],
        direction: [{ required: true, message: '请选择方向', trigger: 'blur' }],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'blur' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'blur' }
        ],
        question: [{ required: true, message: '请输入提干', trigger: 'blur' }],
        answer: [
          { required: true, message: '请输入答案解析', trigger: 'blur' }
        ]
      },
      editorOptions: {
        // 占位配置
        placeholder: '',
        modules: {
          // 工具栏
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            ['blockquote', 'code-block'],
            [{ header: 1 }, { header: 2 }],
            [{ list: 'ordered' }, { list: 'bullet' }],
            [{ indent: '-1' }, { indent: '+1' }],
            ['image']
          ]
        }
      },
      editData: {}
    };
  },
	created() {
    this.getSubList();
    this.getCompanys();
	},
	async mounted() {
    if (this.$route.params.id) {
			console.log(111);
      const res = await getBasicQuestionDetailAPI(this.$route.params.id);
      const {
        subjectID,
        catalogID,
        enterpriseID,
        province,
        city,
        direction,
        questionType,
        difficulty,
        question,
        answer,
        options,
        videoURL,
        remarks,
        tags
      } = res;
      this.editData = res;
      await this.subValueChange(subjectID);
      this.formData.subjectID = subjectID;
      this.formData.catalogID = catalogID;
      this.formData.enterpriseID = enterpriseID;
      this.formData.province = province;
      this.formData.city = city;
      this.formData.direction = direction;
      this.formData.questionType = questionType;
      this.formData.difficulty = difficulty;
      this.formData.question = question;
      this.formData.answer = answer;
      this.formData.videoURL = videoURL;
      this.formData.remarks = remarks;
      this.formData.tags = tags;

      // 先判断是否是单选
      if (res.questionType === '1') {
        options.forEach((item) => {
          if (item.isRight === 1) {
            this.formData.optionVal = item.code;
          }
        });
        for (var i = 0; i <= options.length - 1; i++) {
          // console.log(options[i]);
          options[i].code = String.fromCharCode(65 + i);
        }
      } else if (res.questionType === '2') {
        for (var j = 0; j <= options.length - 1; j++) {
          // console.log(options[i]);
          options[j].code = String.fromCharCode(65 + j);
        }
        this.formList.options = options;
      }
      options.map((item) => {
        if (item.isRight === 1) {
          item.isRight = true;
        } else {
          item.isRight = false;
        }
      });
    }
  },
methods: {
    // 选择城市的方法
    changeFn() {
      // 获取地区赋值给本地
      this.citysList = citys(this.formData.province);
    },

    // 获取学科目录

    async getSubList() {
      this.formList.subData = await getSubjectsListAPI();
    },

    // 二级目录

    async subValueChange(result) {
      this.formList.secondData = await getSubjectsAPI(result);
      this.formList.labelList = await getlabelListAPI(result);
      this.formData.catalogID = '';
      this.formData.tags = '';
    },

     // 获取企业目录

    async getCompanys() {
      const { items } = await getCompanyListAPI(1000);
      this.formList.companys = items;
    },
    addChild() {
      const n =
        this.formList.options[
          this.formList.options.length - 1
        ].code.charCodeAt();
      const code = String.fromCharCode(n + 1);
      this.formList.options.push({
        isRight: false,
        code: code,
        title: '',
        img: ''
      });
    },
		// 点击添加按钮，添加试题
    addClick() {
      const {
        answer,
        catalogID,
        city,
        difficulty,
        direction,
        enterpriseID,
        province,
        question,
        questionType,
        remarks,
        subjectID,
        videoURL
      } = this.formData;
      this.$refs.form.validate(async(isok) => {
        if (isok) {
          console.log(this.formList.options);
          try {
            await addBasicQuestionAPI({
              answer: answer,
              catalogID: catalogID,
              city: city,
              difficulty: difficulty,
              direction: direction,
              enterpriseID: enterpriseID,
              options: this.formList.options,
              province: province,
              question: question,
              questionType: questionType,
              remarks: remarks,
              subjectID: subjectID,
              tags: this.$refs.label.valueKey,
              videoURL: videoURL
            });
            this.$message.success('添加成功');
            this.$router.push('/testing/basisTesting');
          } catch (error) {
            console.log(error);
          }
        } else {
          console.log('请输入完整信息');
        }
      });
    },
		// 点击修改按钮，修改试题
    async editClick() {
      const {
        answer,
        catalogID,
        city,
        difficulty,
        direction,
        enterpriseID,
        province,
        question,
        questionType,
        remarks,
        subjectID,
        videoURL,
        tags
      } = this.formData;
      try {
        await updateBasicQuestionAPI(this.$route.params.id, {
          addDate: this.editData.addDate,
          chkDate: this.editData.chkDate,
          chkRemarks: this.editData.chkRemarks,
          chkState: this.editData.chkState,
          chkUserID: this.editData.chkUserID,
          id: this.editData.id,
          isChoice: this.editData.isChoice,
          number: this.editData.number,
          publishState: this.editData.publishState,
          answer: answer,
          catalogID: catalogID,
          city: city,
          difficulty: difficulty,
          direction: direction,
          enterpriseID: enterpriseID,
          options: this.formList.options,
          province: province,
          question: question,
          questionType: questionType,
          remarks: remarks,
          subjectID: subjectID,
          tags: tags,
          videoURL: videoURL
        });
        this.$message.success('修改成功');
        this.$router.push('/questions/basics');
      } catch (error) {
        console.log(error);
      }
    },
		// 单选框改变时触发的事件
    radioValueChange(res) {
      this.formList.options.forEach((item) => {
        if (item.code === res) {
          item.isRight = true;
        } else {
          item.isRight = false;
        }
      });
      console.log(res);
    }
  }
}
</script>

<style lang='scss' scoped>
.app-container{
	padding: 15px;
}
::v-deep .el-form{
	padding-left: 20px;
}
::v-deep .el-card__body{
	padding-top: 13px;
}
.title{
	height: 30px;
	border-bottom: 1px solid #ccc;
	margin-bottom: 10px;
}
.select{
	height: 35px;
}
.sml_title{
	display: inline-block;
	width: 75px !important;
	font-size: 15px;
	margin: 0 15px 10px 0;
}
.Analytic_video{
	height: 40px;
	::v-deep .el-input{
		width: 500px;
	}

}
.Subject_remark{
	height: 50px;
	width: 1000px;
	margin-top: 160px;
}
.body{
	width: 1000px;
	height: 200px;
	float: right;
	margin-right: 127px;
}
::v-deep .quill-editor {
	width: 1000px;
	height: 200px;
}
::v-deep .ql-toolbar{
	height: 40px;
}
::v-deep .ql-container {
	height: 150px;
}
::v-deep .el-textarea{
		float: right;
	width: 500px;
		margin-right: 410px;

}


.group {
  position: relative;
}
.Img {
  display: inline-block;
  margin-left: 10px;
  position: absolute;
  bottom: -14px;
}
::v-deep .el-form-item__label {
  padding: 0 9px 0 0;
}
</style>